package com.zhang.bingmei_incomeexpenditure.entity.commom;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.io.ByteArrayInputStream;
import java.sql.*;

/**
 * 自定义类型处理器：将数据库BLOB类型转换为Java String
 */
public class BlobToStringHandler extends BaseTypeHandler<String> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        // 插入/更新时，将String转为BLOB（根据实际需求实现，若不需要可留空）
        ps.setBlob(i, new ByteArrayInputStream(parameter.getBytes()));
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        // 查询时，将BLOB转为String
        Blob blob = rs.getBlob(columnName);
        if (blob != null) {
            return new String(blob.getBytes(1, (int) blob.length()));
        }
        return null;
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Blob blob = rs.getBlob(columnIndex);
        if (blob != null) {
            return new String(blob.getBytes(1, (int) blob.length()));
        }
        return null;
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Blob blob = cs.getBlob(columnIndex);
        if (blob != null) {
            return new String(blob.getBytes(1, (int) blob.length()));
        }
        return null;
    }
}